<template>
  <div>
<!--    面包屑-->
    <bread-list :navData="navData"></bread-list>
<!--    卡片视图区域-->
    <el-card>
<!--      警告区域-->
      <el-alert
          title="注意: 只允许为第三级分类设置相关参数!"
          show-icon
          :closable="false"
          type="warning">
      </el-alert>
      <el-row>
<!--        商品分类参数-->
        <el-col style="margin-top: 15px">
          <span>选择商品分类：</span>
          <el-cascader style="width: 20%"
              v-model="selectedKeys"
              :options="cateGoryList"
              :props="cateGoryProps"
              clearable
              show-all-levels
              @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
<!--      动态属性和静态属性-->
      <el-row style="margin-top: 15px">
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleClick">
<!--            添加动态属性面板-->
            <el-tab-pane label="动态配置" name="many">
              <el-button :disabled="selectedKeys.length!==3" type="primary" size="mini" @click="addParams">添加参数</el-button>
              <!--      动态参数表格-->
              <el-table :data="manyCateParamsList" border stripe>
<!--                展开行-->
                <el-table-column :default-expand-all="true"  align="center" type="expand">
                  <template slot-scope="scope">
                    <el-tag @close="deleteParamsTag(scope.row,index)" closable v-show="scope.row.attr_vals !== ''" class="catParamsTag" v-for="(item,index) in scope.row.attr_vals.split(',')" :key="index">{{ item }}</el-tag>
<!--                    //输入的文本框-->
                    <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
<!--                    添加按钮-->
                    <el-button v-else class="button-new-tag catParamsTag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <!--        索引列-->
                <el-table-column label="#" align="center" type="index"></el-table-column>

                <el-table-column label="参数名称" align="center" prop="attr_name"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateParams(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
                  </template>
                </el-table-column>

              </el-table>
            </el-tab-pane>
<!--            添加静态属性面板-->
            <el-tab-pane label="静态配置" name="only">
              <el-button :disabled="selectedKeys.length!==3" type="primary" size="mini" @click="addAttr">添加属性</el-button>
              <!-- 静态参数表格-->
              <el-table :data="onlyCateParamsList" border stripe v-show="activeName === 'only'">
                <el-table-column :default-expand-all="true"  align="center" type="expand">
                  <template slot-scope="scope">
                    <el-tag @close="deleteParamsTag(scope.row,index)" closable v-show="scope.row.attr_vals !== ''" class="catParamsTag" v-for="(item,index) in scope.row.attr_vals.split(',')" :key="index">{{ item }}</el-tag>
                    <!--                    //输入的文本框-->
                    <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <!--                    添加按钮-->
                    <el-button v-else class="button-new-tag catParamsTag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>

                <!--索引列-->
                <el-table-column label="#" align="center" type="index"></el-table-column>
                <el-table-column label="参数名称" align="center" prop="attr_name"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCateAttr(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>


    </el-card>

<!--    新增分类对话框-->

    <el-dialog
        :title="title"
        :visible.sync="addParamsDialogVisible"
        @close="handleClose"
        width="25%">
      <el-form  :model=" activeName === 'many' ? manyCateParams : onlyCateParams" :rules="addCateParamsRules" ref="addCateParamsRefForm" label-width="80px" status-icon>
        <el-form-item :label="label" :prop=" activeName=== 'many' ? 'manyParams' : 'onlyParams' " label-width="80px">
          <el-input v-if="activeName === 'many' " clearable v-model="manyCateParams.manyParams"></el-input>
          <el-input v-else clearable v-model="onlyCateParams.onlyParams"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="addParamsDialogVisible = false">取 消</el-button>
      <el-button type="primary"  @click="addManyCateParams">确 定</el-button>
     </span>
    </el-dialog>

<!--    编辑对话框-->
    <el-dialog
        :title="title"
        :visible.sync="editParamsDialogVisible"
        width="25%">
      <el-form  :model=" activeName === 'many' ? manyCateParams : onlyCateParams" :rules="addCateParamsRules" ref="editCateParamsRefForm" label-width="80px" status-icon>
        <el-form-item :label="label" :prop=" activeName=== 'many' ? 'manyParams' : 'onlyParams' " label-width="80px">
          <el-input v-if="activeName === 'many' " clearable v-model="manyCateParams.manyParams"></el-input>
          <el-input v-else clearable v-model="onlyCateParams.onlyParams"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="editParamsDialogVisible = false">取 消</el-button>
      <el-button type="primary"  @click="editParams">确 定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadList from "../common/BreadList";
export default {
  name: "GoodsParams",
  components:{
    BreadList
  },
  data(){
    return{
      navData:{
        navNameFir:'商品',
        navSecond:'商品参数',
        path:'/home'
      },
      // 商品分类列表
      cateGoryList:[],
      // 当前已选择的分类id
      selectedKeys:[],
      //练级选择项配置
      cateGoryProps:{
        label:'cat_name',
        value:'cat_id',
        children:'children',
      },
      // 当前参数对象
      // currentParams:{},
      activeName:'many',
      manyCateParamsList:[],
      onlyCateParamsList:[],
      addParamsDialogVisible:false,
      onlyCateParams:{
        onlyParams:'' // 静态参数
      },
      manyCateParams:{
        manyParams:'' //动态参数
      },
      editParamsDialogVisible:false,
      // 对话框标题
      title:'',
      attrId:0,
      // 对话框label
      label:'',
      addCateParamsRules:{
        manyParams:[
          { required:true, message:'请输入分类参数',trigger:'blur' }
        ],
        onlyParams:[
          { required:true, message:'请输入静态属性',trigger:'blur' }
        ]
      },
      // // 控制按钮
      // inputVisible:false,
      // // 文本框显示的值
      // inputValue:'',
    }
  },
  mounted() {
    this.getCateGoryList()
  },
  computed:{
    // 三级分类id
    catId(){
      if(this.selectedKeys.length === 3){
        return this.selectedKeys[2]
      }
      return null
    }
  },
  methods:{
    // 获取参数分类3级
    async getCateGoryList(){
      const {data:res} = await this.$http.get('categories')
      const { data:data ,meta:meta } = res
      if(meta.status === 200){
        this.cateGoryList = data
      }else {
        this.$message.error(meta.msg)
      }
      // meta.status === 200 ? this.cateGoryList = data  : this.$message.error(meta.msg)
    },
    // 监听级联选择
    handleChange(){
      if(this.selectedKeys.length !==3){
        this.$message.warning('只允许为第三级分类设置相关参数')
        this.selectedKeys = []
        this.manyCateParamsList = []
        this.onlyCateParamsList = []
      }else {
        this.getParamsList()

      }
      console.log(this.selectedKeys);
    },
    //
    handleClick(){
      if(this.selectedKeys.length === 3){
        this.getParamsList()
      }else {
        this.$message.error('请先选择三级分类')
        return
      }
    },
    // 获取参数列表
    async getParamsList(){
      const { data:res } = await this.$http.get('categories/'+ this.catId +'/attributes',{params:{sel:this.activeName}})
      if(res.meta.status === 200){
        if(this.activeName === 'many'){
          res.data.forEach((item) =>{
            item.inputVisible = false
            item.inputValue = ''
          })
          this.manyCateParamsList = res.data

        }else {
          res.data.forEach((item) =>{
            item.inputVisible = false
            item.inputValue = ''
          })
          this.onlyCateParamsList = res.data
        }
      }else {
        this.$message.error(res.meta.msg)
      }
      // console.log(res);
    },
    // 点击添加按钮 打开对话框
    addParams(){
      this.title = '添加动态参数'
      this.label = '动态参数'
      this.addParamsDialogVisible = true
    },
    // 关闭弹窗，清空
    handleClose(){
      this.$refs.addCateParamsRefForm.resetFields()
    },
    addManyCateParams(){
        this.$refs.addCateParamsRefForm.validate( valid =>{
          if(valid){
            this.addCateParams()
          }else {
            return
          }
        })

    },
    // 添加动态参数
    async addCateParams(){
      let attr_name = ''
      if(this.activeName === 'many'){
        attr_name = this.manyCateParams.manyParams
      }else {
        attr_name = this.onlyCateParams.onlyParams
      }
      const  {data:res} = await  this.$http.post('categories/' + this.catId + '/attributes',{attr_name:attr_name,attr_sel:this.activeName})
      if(res.meta.status === 201){
        this.addParamsDialogVisible = false
        this.$message.success(res.meta.msg)
        await this.getParamsList()
        this.manyCateParams = {}
        this.onlyCateParams = {}
      }else {
        this.$message.error(res.meta.msg)
      }
    },
    addAttr(){
      this.title = '添加静态属性'
      this.label = '静态属性'
      this.addParamsDialogVisible = true
    },
    editCateParams(manyParamsInfo){
      this.title = '修改动态参数'
      this.label = '动态参数'
      this.attrId = manyParamsInfo.attr_id
      this.manyCateParams.manyParams = manyParamsInfo.attr_name
      this.editParamsDialogVisible = true
      console.log(this.manyCateParams);
    },
    editCateAttr(onlyParamsInfo){
      this.title = '修改静态属性'
      this.label = '静态属性'
      this.attrId = onlyParamsInfo.attr_id
      this.onlyCateParams.onlyParams = onlyParamsInfo.attr_name
      this.editParamsDialogVisible = true
      console.log(onlyParamsInfo);
    },
    // 提交修改表单
     editParams(){
      this.$refs.editCateParamsRefForm.validate( valid =>{
        if(valid){
          this.setCateParams()
        }else{
          return
        }
      })
    },
    //调用修改参数接口
    async setCateParams(){
      let attr_name = ''
      if(this.activeName === 'many'){
        attr_name = this.manyCateParams.manyParams
      }else {
        attr_name = this.onlyCateParams.onlyParams
      }
      const {data:res} = await this.$http.put('categories/'+ this.catId +'/attributes/'+ this.attrId,{attr_name:attr_name,attr_sel:this.activeName})
      const {meta:meta } = res
      if(meta.status === 200){
        this.$message.success(meta.msg)
        this.editParamsDialogVisible = false
        await this.getParamsList()
      }else {
        this.$message.error(meta.msg)
      }
      console.log(res);
    },
    // 删除参数
    async deleteParams(cateParamsInfo){
      this.attrId = cateParamsInfo.attr_id
      const confirm = await this.$confirm('此操作将永久删除' + cateParamsInfo.attr_name +  '参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirm);
      if(confirm === 'confirm'){
         await this.deleteCateParams()
      }else {
        this.$message.info('已取消删除')
      }
    },

    // 调用删除Api
    async deleteCateParams(){
      const { data:res } = await this.$http.delete('categories/'+ this.catId + '/attributes/' + this.attrId)
      console.log(res.meta.status);
      if(res.meta.status === 200){
        this.$message.success(res.meta.msg)
        await this.getParamsList()
      }else {
        this.$message.error(res.data.msg)
      }

      // console.log(res);
    },
    //文本框失去焦点或者按下enter键
    handleInputConfirm(row){
      if(row.inputValue.trim().length === 0){
        row.inputValue = ''
        row.inputVisible = false
      }else {
        // 用户输入了内容
        if(row.attr_vals === ''){
          row.attr_vals = row.inputValue
        }else {
          row.attr_vals = row.attr_vals + ',' + row.inputValue
        }
        row.inputValue = ''
        row.inputVisible = false
        //发起请求，保存更改
        this.addParamsByTag(row.attr_id,row.attr_name,row.attr_vals)
      }
    },
    // 点击按钮，显示文本框
    showInput(row){
      row.inputVisible = true
      // $nextTick 只有当页面重新渲染过后才会触发回调
      this.$nextTick(()=>{
        this.$refs.saveTagInput.$refs.input.focus();
      })
      console.log(row);
    },
    // 编辑提交用户参数
    async addParamsByTag(id,attr_name,attr_vals){
      const { data:res } = await this.$http.put('categories/' + this.catId + '/attributes/' + id,{attr_name:attr_name,attr_vals:attr_vals,attr_sel:this.activeName})
      const { meta:meta } = res
      meta.status === 200 ? this.$message.success(meta.msg)  : this.$message.error(meta.msg)
      // console.log(res);
    },
    // 删除tag
    async deleteParamsTag(row,id){
      console.log(row,id)
      const attrVals = row.attr_vals.split(',')
      const confirm = await this.$confirm('此操作将永久删除' + attrVals[attrVals.length-1] +  '参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirm === 'confirm'){
        attrVals.splice(id,1)
        await this.addParamsByTag(row.attr_id, row.attr_name, attrVals.join(','))
        row.attr_vals = attrVals.join(',')
      }else {
        this.$message.info('已取消删除！')
      }
      console.log(confirm);
    }
  }
}
</script>

<style scoped lang="css">
    .catParamsTag{
      margin: 15px;
    }
    .input-new-tag{
      width: 120px;
      margin-left: 15px;
    }
</style>